/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gen2phen.labs.services;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 *
 * @author pedrolopes
 *
 * GEN2PHEN Semantic Web Labs: Knowledge Netowork
 *
 */
public class Freebase {

    /**
     * Search Freebase for a given search term.
     *
     * @param query The search query.
     * @return Freebase results in JSON format (for client-side JavaScript processing)
     */
    public static String search(String query) {
        String response = "";

        // load results directly from REST Service, no middleware packages
        try {
            URL u = new URL("http://www.freebase.com/api/service/search?query=" + query);
            URLConnection free = u.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(free.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response += inputLine;
            }
            in.close();

        } catch (Exception e) {
            System.out.println("[Freebase] Search Error " + e.toString());
        }

        return response;
    }

    /**
     * Get Freebase value for a given GUID.
     *
     * @param guid The parsed Freebase GUID
     * @return The Freebase value (a text string with max 10000 chars)
     */
    public static String get(String guid) {
        String response = "";

        // use direct REST service instead of middleware package
        try {
            URL u = new URL("http://www.freebase.com/api/trans/blurb/guid/" + guid + "?maxlength=10000");
            URLConnection free = u.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(free.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response += inputLine;
            }
            in.close();
        } catch (Exception e) {
            System.out.println("[Freebase] Get Error " + e.toString());
        }

        return response;
    }
}
